<template>
  <div class="app-container">
    <h4 class="form-header h4">基本信息</h4>
    <!-- 添加 v-if 条件渲染 -->
    <el-form ref="form" :model="form" label-width="80px" v-if="form">
      <el-row>
        <el-col :span="8" :offset="2">
          <el-form-item label="用户昵称" prop="nickName">
            <el-input v-model="form.nickName" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="8" :offset="2">
          <el-form-item label="登录账号" prop="userName">
            <el-input v-model="form.userName" disabled/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <h4 class="form-header h4">病患信息</h4>
    <el-table v-loading="loading" :row-key="getRowKey" @row-click="clickRow" ref="table"
              @selection-change="handleSelectionChange" :data="about.slice((pageNum-1)*pageSize,pageNum*pageSize)"
    >
      <!--      <el-table-column label="序号" type="index" align="center">-->
      <!--        <template slot-scope="scope">-->
      <!--          <span>{{ (pageNum - 1) * pageSize + scope.$index + 1 }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column type="selection" :reserve-selection="true" width="55"></el-table-column>-->
      <el-table-column label="病患编号" align="center" prop="patientId"/>
      <el-table-column label="病患名称" align="center" prop="childName"/>
      <el-table-column label="生日" align="center" prop="birth" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.birth, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- 新增年龄字段 -->
      <el-table-column label="年龄" align="center" width="80">
        <template slot-scope="scope">
          <span>{{ calculateAge(scope.row.birth) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="居住地" align="center" prop="address"/>
      <el-table-column label="所用量表" align="center" width="250px" prop="scaleName">
        <template slot-scope="scope">
          <el-tooltip
            :content="scope.row.scale ? scope.row.scale.replace(/◆/g, '\n') : '-'"
            effect="light"
            placement="top"
            :disabled="!scope.row.scale"
          >
            <div class="scale-content">
              {{ scope.row.scale ? scope.row.scale.replace(/◆/g, ' ') : '-' }}
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
        <template slot-scope="scope" v-if="scope.row.userId != 1">
          <el-button size="mini" type="text" icon="el-icon-edit"
                     @click="updateScale(scope.row)" v-hasPermi="['system:user:edit']"
          >修改量表
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="pageNum" :limit.sync="pageSize"/>

    <el-form label-width="100px">
      <el-form-item style="text-align: center;margin-left:-120px;margin-top:30px;">
        <el-button type="primary" @click="submitForm1()">提交</el-button>
        <el-button @click="close()">返回</el-button>
      </el-form-item>
    </el-form>

    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form1" :model="form1" :rules="rules" label-width="80px">
        <!--        <el-form-item label="病患名称" prop="childName">-->
        <!--          <el-input v-model="form1.childName" placeholder="请输入病患名称" disabled/>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="生日" prop="birth">-->
        <!--          <el-input v-model="form1.birth" placeholder="请输入生日" disabled/>-->
        <!--        </el-form-item>-->
        <!--        &lt;!&ndash; 新增年龄显示项 &ndash;&gt;-->
        <!--        <el-form-item label="年龄">-->
        <!--          <el-input v-model="form1.age" placeholder="自动计算" disabled/>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="地址" prop="address">-->
        <!--          <el-input v-model="form1.address" placeholder="请输入地址" disabled/>-->
        <!--        </el-form-item>-->
        <el-form-item label="量表名称" prop="scaleName">
          <el-select v-model="assignedScaleIds" multiple clearable placeholder="请输入量表名称">
            <el-option
              v-for="item in scaleNames"
              :key="item.scaleId"
              :value="item.scaleId"
              :label="item.scaleName"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listScale } from '@/api/dcp/scale'
import { getAuthRole } from '../../../api/system/user'
import { addScaleScreen, listPatient } from '../../../api/dcp/patient'

export default {
  name: 'AuthAbout',
  data() {
    return {
      assignedScaleIds: [],
      scaleNames: [],
      // 遮罩层
      loading: true,
      // 分页信息
      total: 0,
      pageNum: 1,
      pageSize: 10,
      // 选中角色编号
      patientIds: [],
      // 角色信息
      about: [],
      // 用户信息
      form: {
        nickName: '',
        userName: ''
      },
      form1: {},
      //弹出层显示
      open: false,
      rules: {},
      title: ''
    }
  },
  created() {
    const userId = this.$route.query.userId
    console.log(userId)
    if (userId) {
      this.loading = true
      // 初始化 form 对象
      this.form = {
        nickName: null,
        userName: null
      }
      this.getList()
      listScale().then(response => {
        this.scaleNames = response.rows
      })
    }
  },
  methods: {
    getList() {
      const userId = this.$route.query.userId
      // 通过userId查询用户
      getAuthRole(userId).then(res => {
        this.form = res.user
        console.log(res.user)
      })
      // 查询病患信息
      this.loading = true
      const user = {
        userId: userId
      }
      listPatient(user).then(res => {
        this.about = res.rows
        console.log(this.about)
        this.loading = false
      })
      // getAuthAbout(userId).then((response) => {
      //   this.form = response.user;
      //   // 计算并添加年龄字段
      //   this.about = response.about.map(item => {
      //     return {
      //       ...item,
      //       age: this.calculateAge(item.birth)
      //     }
      //   });
      //   this.total = this.about.length;
      //   this.$nextTick(() => {
      //     this.about.forEach((row) => {
      //       if (row.flag) {
      //         this.$refs.table.toggleRowSelection(row);
      //       }
      //     });
      //   });
      //   this.loading = false;
    },
    /**
     * 修改量表*/
    updateScale(row) {
      this.reset()
      this.form1.patientId = row.patientId
      this.form1.patientName = row.childName
      console.log(row)
      this.open = true
      this.title = '修改量表'
      // getAuthAbout1(patientId).then(response => {
      //   this.form1 = response.about[0]
      //   // 计算并设置年龄
      //   this.form1.age = this.calculateAge(this.form1.birth)
      //   listScale().then(response => {
      //     this.scaleNames = response.rows
      //   })
      //   this.open = true
      //   this.title = '修改量表'
      // })
    },
    /** 计算年龄 */
    calculateAge(birthDate) {
      if (!birthDate) return ''

      // 解析生日字符串，格式为 YYYY-MM-DD
      const [year, month, day] = birthDate.split('-').map(Number)
      const birth = new Date(year, month - 1, day)
      const today = new Date()

      // 计算年龄
      let age = today.getFullYear() - birth.getFullYear()
      const monthDiff = today.getMonth() - birth.getMonth()

      // 如果生日还没过，则减一岁
      if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
        age--
      }

      return age
    },
    /** 单击选中行数据 */
    clickRow(row) {
      this.$refs.table.toggleRowSelection(row)
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.patientIds = selection.map((item) => item.patientId)
    },
    // 保存选中的数据编号
    getRowKey(row) {
      return row.patientId
    },
    //表单重置
    reset() {
      this.form1 = {
        patientId: null,
        childName: null,
        birth: null,
        age: null, // 添加年龄字段
        address: null,
        scaleName: null
      }
      // this.resetForm('form1');
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form1'].validate(valid => {
        if (valid) {
          if (this.form1.patientId != null) {
            let arr = []
            for (let i = 0; i < this.assignedScaleIds.length; i++) {
              // 在量表列表中查找匹配项
              const scale = this.scaleNames.find(
                item => item.scaleId === this.assignedScaleIds[i]
              )

              let params = {
                scaleId: this.assignedScaleIds[i],
                scaleName: scale ? scale.scaleName : '未知量表',
                patientId: this.form1.patientId,
                patientName: this.form1.patientName,
                status: 0
              }
              arr.push(params)
            }
            console.log(arr)
            addScaleScreen(arr).catch(error => {
              this.$message.error('量表分配失败: ' + error.message)
              throw error // 保持错误传递
            })
            this.open = false
            this.$message.success('量表分配成功')
            this.getList()
            // let params = {
            //   scaleId: this.form1.scaleId,
            //   scaleName: scale ? scale.scaleName : '未知量表',
            //   patientId: this.form.patientId,
            //   patientName: this.form.childName,
            //   status: 0
            // }
            // const params = {
            //   patientId: this.form1.patientId,
            //   scaleName: this.form1.scaleName
            // }

            // updateAuthAbout(params).then(response => {
            //   this.$modal.msgSuccess('修改成功')
            //   this.open = false
            //   this.getList()
            // })
          }
        }
      })
    },
    submitForm1() {
      this.$modal.msgSuccess('提交成功')
      const obj = { path: '/system/user' }
      this.$tab.closeOpenPage(obj)
    },
    /** 关闭按钮 */
    close() {
      const obj = { path: '/system/user' }
      this.$tab.closeOpenPage(obj)
    },
    cancel() {
      this.open = false
    }
  }
}
</script>
<style>
.scale-content {
  display: -webkit-box;
  -webkit-line-clamp: 3; /* 控制显示行数 */
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  max-height: 60px; /* 行高×行数 */
  line-height: 20px;
  text-align: left;
  white-space: normal !important;
}
</style>
